<template>
  <div>
    <ul class="week">
      <li v-for="(item,index) in week" :key="item">
        {{item}}
        {{panelDateList[0][index]}}
      </li>
    </ul>
    <div class="calendar-panel">
      <div class="row" :style="panelRowHeight" v-for="(row, index) in panelDateList" :key="index+'row'">
        <div class="date-row">
          <template v-for="(item, subIndex) in row">
          <div @contextmenu.prevent class="date last-month" v-if="index === 0 && item > 7" :key="item*(index+1)"
               @click="addSchedule(item,'last',subIndex)">{{item}}日</div>
          <div @contextmenu.prevent class="date next-month" v-else-if="(index === 5 || index === 4) && item < 7"
               :key="item*(index+1)" @click="addSchedule(item,'next',subIndex)">{{item}}日</div>
          <div  class="date" @contextmenu.prevent="showMenu(item,'current',subIndex,index)" v-else :key="item*(index+1)">
            <span :class="[item===today && isThisMonth ? 'today' : '' ]">{{item}}</span>日
            <vue-context-menu :contextMenuData="contextMenuData"
                              @add="addScheduleModel"
                              @edit="addScheduleModel"
                              @del="deleteSchedule"
                              @detail="detailScheduleModel"
                             ></vue-context-menu>

          </div>
          </template>
        </div>
        <!--日程显示-->
        <div class="schedule-row"  @contextmenu.prevent>
          <div class="schedule-row-item" v-for="(daySchedule,inx) in getScheduleList[index]" :key="inx">
            <div v-if="daySchedule.length > 0" v-for="(schedule,inxs) in daySchedule"
                 :key="inxs" >
              <span :class="scheduleTheme[schedule.group]" @click="menuSchedule(schedule,inxs,inx)">{{schedule.content}}</span>
            </div>
            <div v-else></div>
          </div>
        </div>
      </div>
    </div>
    <!--日程弹窗-->
    <model-schedule :x="contextMenuData.axis.x" :y="contextMenuData.axis.y"
                    :col="contextMenuData.axis.col" :row="contextMenuData.axis.row"
                    :day="contextMenuData.axis.day" :contents="content" :groups="group"
                    :beginTime="beginTime" :endTime="endTime"
                    v-if="visible" @cancel="cancel" @addSchedules="addSchedules" @editSchedules="editSchedules"/>
    <!--日程详情弹窗-->
    <model-schedule-detail :x="contextMenuData.axis.x" :y="contextMenuData.axis.y"
                    :col="contextMenuData.axis.col" :row="contextMenuData.axis.row"
                    :day="contextMenuData.axis.day" :contents="content" :groups="group"
                    :beginTime="beginTime" :endTime="endTime"
                    v-if="detailVisible" @cancel="cancel" />
  </div>
</template>

<script>
  import moment from 'moment'
  import { getNumberOfDaysInMonth } from "./tools/getNumberOfDaysInMonth"
  import scheduleList from './mock/schedule'
  import ModelSchedule from "./tools/ModelSchedule";
  import ModelScheduleDetail from "./tools/ModelScheduleDetail.vue";
  export default {
    name: "Calendar",
    components:{
      ModelSchedule,
      ModelScheduleDetail
    },
    props: {
      viewType: String,
      currentDate: Date
    },
    data () {
      return {
        visible:false,
        detailVisible:false,
        content:"",
        group:0,
        beginTime:'00:00',
        endTime:moment(new Date()).format('HH:mm'),
        editId:null,
        week: ['周日','周一','周二','周三','周四','周五','周六'],
        today: new Date().getDate(),
        scheduleList: scheduleList,
        scheduleTheme: 'blue,grayGreen,orange,red,purple,fuchsia'.split(','),
        // 菜单数据
        contextMenuData: {
          menuName: 'demo',
          //菜单显示的位置
          axis: {
            x: null,
            y: null,
            col: null,
            row: null,
            day:null
          },
          //菜单选项
          menulists: [
            {
              fnHandler: 'add', //绑定事件
              // icoName: 'fa fa-home fa-fw', //icon图标
              btnName: '新建日程' //菜单名称
            },
            /*{
              fnHandler: 'deletedata',
              // icoName: 'fa fa-minus-square-o  fa-fw',
              btnName: '编辑日程'
            }*/
          ]
        }
      }
    },
    computed: {
      panelRowHeight () {
        // 日历面板 每行高度
        return `height: ${(window.innerHeight - 100)/6}px`
      },
      currentMonthDays () {
        return [...Array(getNumberOfDaysInMonth(this.currentDate))].map((v,k) => k + 1)
      },
      lastMonthDays () {
        // 上个月天数
        const lastMonth = new Date().setMonth(new Date(this.currentDate.setDate(1)).getMonth() - 1)
        const daysNumber = getNumberOfDaysInMonth(lastMonth)
        // 根据当前月1日 计算 日历面板 上个月天数
        const panelNumberLastMonth = this.getDayOfMonthOn1st()
        const daysArr = []
        for (let i = 0; i < panelNumberLastMonth; i++) {
          daysArr.splice( 0, 0, daysNumber - i)
        }
        return daysArr
      },
      nextMonthDays () {
        // 根据当前月最后1日 计算 日历面板 下个月天数
        const panelNumberLastMonth = 6 - this.getDayOfMonthOnLastDay()
        const daysArr = []
        for (let i = 0; i < panelNumberLastMonth; i++) {
          daysArr.push( i + 1)
        }
        return daysArr
      },
      panelDateList () {
        const fullList = this.lastMonthDays.concat(this.currentMonthDays, this.nextMonthDays)
        const result = []
        for (let i=0;i< fullList.length; i+=7) {
          result.push(fullList.slice(i,i+7))
        }
        return result
      },
      isThisMonth () {
        // return true
        if (new Date().getMonth() === this.currentDate.getMonth() && new Date().getFullYear() === this.currentDate.getFullYear()) {
          return true
        } else{
          return false
        }
      },
      dateTypeFullList () {
        const result = []
        const lastMonth = new Date().setMonth(new Date(this.currentDate.setDate(1)).getMonth() - 1)
        const nextMonth = new Date().setMonth(new Date(this.currentDate.setDate(1)).getMonth() + 1)
        this.lastMonthDays.forEach(item => {
          result.push(new Date(lastMonth).setDate(item))
        })
        this.currentMonthDays.forEach(item => {
          result.push(this.currentDate.setDate(item))
        })
        this.nextMonthDays.forEach(item => {
          result.push(new Date(nextMonth).setDate(item))
        })
        return result
      },
      getScheduleList () {
        const result = [];
        this.dateTypeFullList.forEach((day,index) => {
          const schedule =
            this.scheduleList.filter(item =>
              moment(item.beginDate).format('YYYYMMDD') === moment(day).format('YYYYMMDD'))
          result.push(schedule)
        })

        const groupResult = []
        for (let i=0;i< result.length; i+=7) {
          groupResult.push(result.slice(i,i+7))
        }
        return groupResult
      },
      currentMonthSchedule () {
        const currentYear = this.currentDate.getFullYear()
        const currentMonth = this.currentDate.getMonth() + 1
        const years = this.scheduleList.find(item =>  item.year === currentYear) || []
        const month = years.list.find(item =>  item.month === currentMonth) || []
        return month.list
      }
    },
    mounted() {

    },
    methods: {
      showMenu (day,month,col,row) {
        if(this.visible){return}
        this.content = "";
        this.group = 0;
        this.beginTime = '00:00';
        this.endTime = moment(new Date()).format('HH:mm');
        this.contextMenuData.menulists =
          [
            {
              fnHandler: 'add',
              // icoName: 'fa fa-minus-square-o  fa-fw',
              btnName: '新建日程'
            }
          ]
        event.preventDefault()
        var x = event.clientX
        var y = event.clientY
        // Get the current location
        this.contextMenuData.axis = {
          x, y,col,row,day
        }
      },
      getDayOfMonthOn1st () {
        const weekDay = new Date(this.currentDate.setDate(1)).getDay()
        return weekDay
      },
      getDayOfMonthOnLastDay () {
        const weekDay = new Date(this.currentDate.setDate(getNumberOfDaysInMonth(this.currentDate))).getDay()
        return weekDay
      },
      addSchedules(content,group,beginDate,endDate){
        let json = {
          id:this.scheduleList[this.scheduleList.length-1].id+1,
          content,group,beginDate,endDate
        };
        this.scheduleList.push(json);
        this.visible = false;
        this.$message.info("新建日程成功！");
      },
      addScheduleModel(){
        this.checkXY();
        this.visible = true;
      },
      detailScheduleModel(){
        this.checkXY();
        this.detailVisible = true;
      },
      checkXY(){
        let x = this.contextMenuData.axis.x;
        let y = this.contextMenuData.axis.y;
        if(this.contextMenuData.axis.col>4){
          x -=420;
        }
        if(this.contextMenuData.axis.row>3){
          y -=270;
        }
        this.contextMenuData.axis.x = x;
        this.contextMenuData.axis.y = y;
      },
      editSchedules(content,group,beginDate,endDate){
        // 更新ID是editId的
        this.scheduleList.forEach((item)=>{
          if(item.id===this.editId){
             item.content = content;
             item.group = group;
             item.beginDate = beginDate;
             item.endDate = endDate;
           }
        })
        this.visible = false;
        this.$message.info("编辑日程成功！");
      },
      addSchedule (day,month,col) {
        if (month === 'current') {
          this.visible = true;
          // 当月
          const date = new Date(this.currentDate.setDate(day))
        }
      },
      menuSchedule(item,index,col){
        if(this.visible){return}
        this.contextMenuData.menulists =
          [
            {
              fnHandler: 'edit',
              // icoName: 'fa fa-minus-square-o  fa-fw',
              btnName: '编辑日程'
            },
            {
              fnHandler: 'del',
              // icoName: 'fa fa-minus-square-o  fa-fw',
              btnName: '删除日程'
            },
            {
              fnHandler: 'detail',
              // icoName: 'fa fa-minus-square-o  fa-fw',
              btnName: '查看日程'
            },
          ]
        let day = new Date(item.beginDate).getDate();
        // event.preventDefault()
        var x = event.clientX
        var y = event.clientY
        let row = day>20?4:2;
        // Get the current location
        this.contextMenuData.axis = {
          x, y,col,row,day
        }
        this.content = item.content;
        this.group = item.group;
        this.beginTime = moment(item.beginDate).format('HH:mm');
        this.endTime = moment(item.endDate).format('HH:mm');
        this.editId = item.id;

      },
      deleteSchedule(){
        let _this = this;
        this.$confirm({
          content: '确定要删除该日程吗？',
          title:"提示",
          cancelText:"取消",
          okText:"确定",
          onOk() {
            _this.scheduleList = _this.scheduleList.filter(item=>item.id!==_this.editId);
            this.$message.info("日程删除成功！");
          },
        });
      },
      cancel(){
        this.visible=false;
        this.detailVisible=false;
      }
    },
  }
</script>

<style lang="less" scoped>
  @import "tools/scheduleTheme";
  @import "tools/scrollbar";
  @LineColor: #E6E5E6;
  @Gray: #B9B9B9;
  @PrimaryColor: #1C72E8;

  ul,li {
    list-style: none;
    padding: 0;
    margin: 0;
  }
  ul.week {
    width: 100%;
    height: 40px;
    display: flex;
    border-bottom: 1px solid @LineColor;
    align-items: flex-end;
    li {
      width: 14.28%;
      text-align: right;
      padding-right: 10px;
    }
  }
  .row {
    display: flex;
    position: relative;
    .date-row {
      display: flex;
      width: 100%;
      height: 100%;
      .date {
        width: 14.28%;
        height: 100%;
        border-left: 1px solid @LineColor;
        border-bottom: 1px solid @LineColor;
        box-sizing: border-box;
        padding: 10px;
        text-align: right;
        .today {
          width: 25px;
          height: 25px;
          display: inline-block;
          background: @PrimaryColor;
          text-align: center;
          color: white;
          border-radius: 50%;
          line-height: 25px;
        }
      }
      .last-month,
      .next-month {
        color: @Gray;
      }
    }
    .schedule-row {
      position: absolute;
      left: 0;
      top: 40px;
      width: 100%;
      display: flex;
      &-item {
        width: 14.8%;
        height: 60px;
        overflow: auto;
      }
    }
  }

  ul.month-view {
    display: flex;
    flex-wrap: wrap;
    height: 600px;
    li {
      flex: auto;
      width: 14.28%;
      border-left: 1px solid @LineColor;
      border-bottom: 1px solid @LineColor;
      box-sizing: border-box;
      line-height: 25px;
      &:nth-child(7n) {
        background: #F5F5F5;
      }
      &:nth-child(7n+1) {
        background: #F5F5F5;
      }
      .date {
        padding: 10px;
        text-align: right;
        span.today {
          width: 25px;
          height: 25px;
          display: inline-block;
          background: @PrimaryColor;
          text-align: center;
          color: white;
          border-radius: 50%;
          line-height: 25px;
        }
      }

      .schedule-item {
        font-size: 14px;
      }
    }
    li.lastMonth,
    li.nextMonth {
      color: #B9B9B9;
    }
  }

</style>
<style>
 .context-menu-list{
   margin:5px 0!important;
 }
 .btn-wrapper-simple{
   height: 20px!important;
   line-height: 20px!important;
 }
 .btn-wrapper-simple:hover{
   color: #fff;
 }
</style>
